<template>
    <div class="poly-container">
        <div class="header">
            <div class="banner">
                <div class="top">
                    <div class="left">
                        <img :src="userInfo.avatar" alt />
                    </div>

                    <div class="right">
                        <p>{{ polyAccount.nickname }}</p>
                        <p>余额合计：{{ polyAccount.full_balance || 0 }}元</p>
                    </div>
                </div>

                <div class="bottom">
                    <span>聚合账号ID：{{ polyAccount.id }}</span>
                    <span>共绑定{{ polyAccount.full_num || 0 }}个</span>
                </div>
                <!--退出图标-->
                <svg class="exit-icon" aria-hidden="true" @click.stop="onExit">
                    <use xlink:href="#icon-tuichu" />
                </svg>
                <!--设置图标-->
                <svg class="setting-icon" aria-hidden="true" @click.stop="toPersonal">
                    <use xlink:href="#icon-setting" />
                </svg>
            </div>

            <!--二维码区-->
            <div class="code" @click="showPolyCode">
                <div class="left">
                    <svg class="code-icon" aria-hidden="true">
                        <use xlink:href="#icon-erweima" />
                    </svg>
                    <span>聚合二维码</span>
                </div>
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-chevronright" />
                </svg>
            </div>
            <!--所有系统-->
            <div class="code" @click="toAllSys">
                <div class="left">
                    <span>查看所有系统</span>
                </div>
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-chevronright" />
                </svg>
            </div>
            <!--流程和使用说明-->
            <div class="code" @click="toExplain">
                <div class="left">
                    <span>聚合账号功能与流程说明(内附聚合账号操作视频)</span>
                </div>
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-chevronright" />
                </svg>
            </div>
            <div class="code" @click="toExplain2">
                <div class="left">
                    <span>解绑已绑定系统、聚合余额(内附视频)</span>
                </div>
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-chevronright" />
                </svg>
            </div>
        </div>
        <div class="main">
            <div class="brand" v-for="(brand, index) in bindList" :key="brand.brand">
                <div class="title">
                    <div class="left">
                        <span>{{ brand.brandname }}</span>
                        <span v-if="index === 0">（默认）</span>
                        <svg
                            v-else
                            class="icon"
                            aria-hidden="true"
                            @click.stop="setDebrand(brand.brand)"
                        >
                            <use xlink:href="#icon-zhiding" />
                        </svg>
                    </div>
                    <!--                    <div class="right" @click.stop="toAllSys" v-if="index === 0">-->
                    <!--                        <span>查看所有系统</span> <svg class="icon" aria-hidden="true"><use xlink:href="#icon-chevronright"></use></svg>-->
                    <!--                    </div>-->
                </div>
                <SysCard
                    :sys="item"
                    v-for="(item, index) in brand.list"
                    :key="item.id"
                    :isDeBrand="item.brand == polyAccount.de_brand"
                    @deleteSys="onDeleteSys"
                    @setDefaultSys="onSetDefaultSys"
                    @polyMoney="showPassword"
                    @click.stop.native="$refs.turnConfirm.show(item)"
                ></SysCard>
            </div>
        </div>

        <div class="footer">
            <!--<div class="note">-->
            <!--聚合账号内各系统为互相绑定关系，新的被推荐人进入聚合账号的一个系统再跳转进入其他品牌系统默认绑定到聚合账号内对应品牌账号下（扫码绑定除外，原有关系不变），同一品牌下有多账号在聚合账号内，以置顶系统为主系统。-->
            <!--</div>-->
            <div class="spread">
                <!--<img :src="urlImg" alt=""/>-->
                <img src="https://iryoss3-0.oss-cn-beijing.aliyuncs.com/static/poly-public.png" alt />
                <!--<img :src="'poly-public' | imageFmt" alt="" />-->
                <p>关注润妍聚合商城公众号</p>
                <p>一键进入，查询更方便。</p>
            </div>
        </div>
        <div class="btnWrapper">
            <div class="bind-apply" @click="toBindApply">系统绑定申请</div>
        </div>

        <!--支付密码-->
        <PassPop
            ref="passpop"
            :amount="parseFloat(operateSys.balance || 0) | moneyFmt"
            @finishPass="polyBalance"
            :showForget="false"
            title="请输入安全密码"
            text="聚合余额后， 该系统余额将全部转账至您的置顶 品牌置顶系统下。"
        />

        <Confirm title="确定退出该聚合帐号？" :isAlert="false" ref="exitConfirm" @confirm="exit"></Confirm>
        <Confirm title="确定跳转至该系统？" :isAlert="false" ref="turnConfirm" @confirm="getTurnToken"></Confirm>
        <Confirm
            title="确定置顶该系统为默认系统？"
            :isAlert="false"
            ref="toppingConfirm"
            @confirm="setBindingStatus(1)"
        ></Confirm>
        <Confirm
            title="确认删除并解绑该系统？"
            :isAlert="false"
            ref="deleteConfirm"
            @confirm="setBindingStatus(2)"
        ></Confirm>
        <Confirm title="余额已经成功转移至默认品牌默认系统" :isAlert="true" ref="alert"></Confirm>

        <polyQrcode ref="code" :polyAccount="polyAccount"></polyQrcode>
    </div>
</template>

<script>
    import { commonMixin } from "@/common/mixin";
    import SysCard from "@/views/User/sys-card";
    import Confirm from "@/components/common/confirm";
    import PassPop from "../../components/common/password-popup";
    import polyQrcode from "./poly-qrcode";
    import api from "@/request/api";
    import { mapMutations } from "vuex";
    import { sysMixin } from "@/common/mixin";
    // import {isIOS} from "@/common/utils";

    export default {
        mixins: [commonMixin, sysMixin],
        name: "poly-account",
        data() {
            return {
                polyAccount: {},
                bindList: [],
                confirmTitle: "",
                isAlert: false,
                operateSys: "",
                firstleave: true
                // urlImg: ''
            };
        },
        props: {
            //聚合帐号id
            aid: {
                type: Number,
                default: 1,
                isRequired: true
            }
        },
        computed: {},
        async created() {
            await this._getPolyInfo();
            await this._getBrandList();
            await this._getBindList();
            //    发请求获取客服二维码
            // this.urlImg = await this.request.get(api.message, {system: this.system})
        },
        mounted() {},
        methods: {
            //聚合帐号info
            _getPolyInfo() {
                return this.request
                    .get(api.polyInfo, { aid: this.aid })
                    .then(res => {
                        this.polyAccount = res;
                        this.setUserInfo(res);
                    })
                    .catch(err => {
                        console.log(err);
                        // this.$toast.fail(err);
                    });
            },
            //品牌列表,用于对应品牌名称
            _getBrandList() {
                return this.request
                    .get(api.message, {})
                    .then(res => {
                        this.brandList = res;
                    })
                    .catch(err => {
                        console.log(err);
                        // this.$toast.fail(err);
                    });
            },
            //绑定列表
            _getBindList() {
                return this.request
                    .get(api.polyBindList, {})
                    .then(res => {
                        //总金钱、总数、默认系统号
                        this.$set(
                            this.polyAccount,
                            "full_balance",
                            res.summary.full_balance
                        );
                        this.$set(
                            this.polyAccount,
                            "full_num",
                            res.summary.full_num
                        );
                        this.$set(
                            this.polyAccount,
                            "de_brand",
                            res.summary.de_brand
                        );
                        //绑定列表处理
                        this.bindList = this.normalizeBindList(res.bind);
                        this.topDebrand();
                        this.topDefaultSys();
                        //根据brandList赋值brandname
                        this.bindList.forEach(item => {
                            for (const brand of this.brandList) {
                                if (item.brand == brand.brand) {
                                    item.brandname = brand.brandname;
                                }
                            }
                        });
                    })
                    .catch(err => {
                        console.log(err);
                        // this.$toast.fail(err);
                    });
            },
            normalizeBindList(data) {
                let brandArr = [];
                if (data.length > 0) {
                    brandArr = data.map(item => {
                        return item.brand;
                    });
                    brandArr = [...new Set(brandArr)];
                    let indexObj = {};
                    brandArr = brandArr.map((item, index) => {
                        indexObj[item] = index;
                        return { brand: item, list: [] };
                    });
                    for (const item of data) {
                        let index = indexObj[item.brand];
                        brandArr[index].list.push(item);
                    }
                }
                return brandArr;
            },
            //置顶默认品牌
            topDebrand() {
                let index = this.bindList.findIndex(item => {
                    return item.brand == this.polyAccount.de_brand;
                });
                let first = this.bindList[index];
                this.bindList.splice(index, 1, this.bindList[0]);
                this.bindList.splice(0, 1, first);
            },
            //置顶默认系统
            topDefaultSys() {
                if (this.bindList.length == 0) return;

                for (const brand of this.bindList) {
                    let index = brand.list.findIndex(item => {
                        return item.status == 1;
                    });
                    let first = brand.list[index];
                    brand.list.splice(index, 1, brand.list[0]);
                    brand.list.splice(0, 1, first);
                }
            },
            onDeleteSys(sys) {
                this.$refs.deleteConfirm.show();
                this.operateSys = sys;
            },
            onSetDefaultSys(sys) {
                this.$refs.toppingConfirm.show();
                this.operateSys = sys;
            },
            //删除绑定帐号（解绑）
            setBindingStatus(status) {
                return this.request
                    .post(api.setBindingStatus, {
                        brand: this.operateSys.brand,
                        system: this.operateSys.system,
                        uid: this.operateSys.uid,
                        status: status //0普通绑定，1默认绑定，2删除状态
                    })
                    .then(res => {
                        if (res) {
                            this._getBindList();
                        }
                    })
                    .catch(err => {
                        this.$toast.fail(err);
                    });
            },
            toBindApply() {
                this.$router.push({
                    name: "bind-apply"
                });
            },
            toAllSys() {
                this.$router.push({
                    name: "all-sys"
                });
            },
            toExplain() {
                //  去账号说明
                this.$router.push({
                    name: "poly-explain"
                });
            },
            toExplain2() {
                //  去
                window.location.href = `http://mp.weixin.qq.com/s?__biz=MzUyNjM5NTcwOA==&mid=100003562&idx=5&sn=0c44aab6019b032a4674cf9a29945122&chksm=7a0e3eb94d79b7af8d31db6959245455a8e6a29a9be40cb5c04401f5211654b70e851d672eda#rd`;
            },
            toPersonal() {
                this.$router.push({
                    name: "poly-personal",
                    query: {
                        aid: this.aid
                    }
                });
            },
            onExit() {
                this.$refs.exitConfirm.show();
            },
            exit() {
                // 退出登录
                this.$store.commit("setUserInfo", ""); // 把本地用户信息删掉就行
                //  更新tokenarray（删除对应的token）
                let tokenArray = JSON.parse(localStorage.getItem("tokenArray"));
                let system = this.$store.state.login.system;
                delete tokenArray[system];
                this.$store.commit("setTokenArray", tokenArray);

                return this.request
                    .post(api.polySignout, {})
                    .then(res => {
                        if (res) {
                            this.$store.commit("setToken", res.token);
                            this.$store.commit(
                                "setTokenType",
                                res.token_type || "2"
                            );

                            this.$router.push({
                                name: "poly-login"
                            });
                        }
                    })
                    .catch(err => {
                        console.log(err);
                        this.$toast.fail(err);
                    });
            },
            showPolyCode() {
                if (this.bindList.length > 0 && this.polyAccount.full_num > 0) {
                    this.$refs.code.show();
                } else {
                    this.$toast("当前聚合帐号没有绑定系统帐号！");
                }
            },
            setDebrand(id) {
                return this.request
                    .post(api.setDebrand, {
                        de_brand: id
                    })
                    .then(res => {
                        if (res) {
                            this._getBindList();
                        }
                    })
                    .catch(err => {
                        this.$toast.fail(err);
                    });
            },
            showPassword(sys) {
                this.operateSys = sys;
                this.$refs.passpop.show();
            },
            polyBalance(pass) {
                // 支付密码验证
                let postData = {
                    transferid: this.operateSys.uid,
                    money: this.operateSys.balance,
                    pay_pass: pass
                };
                this.request.post(api.polyBalance, postData).then(res => {
                    if (res.status) {
                        this.$refs.alert.show();
                        this._getBindList();
                    } else {
                        this.$toast(res.msg);
                    }
                });
            },
            //获取聚合跳普通系统的token
            getTurnToken(brand) {
                this.request
                    .post(api.turnToSystem, {
                        system: brand.system,
                        uid: brand.uid
                    })
                    .then(res => {
                        if (res) {
                            this.turnSystem(res);
                        }
                    });
            },
            //聚合跳普通系统
            turnSystem({ system, token }) {
                this.$router.replace({
                    name: "welcome",
                    query: {
                        system: system,
                        token: token,
                        token_type: 1,
                        isTurn: true
                    }
                });
            },
            ...mapMutations(["setUserInfo", "setToken"])
        },
        watch: {},
        // 导航离开该组件的对应路由时调用
        beforeRouteLeave(to, from, next) {
            if (this.firstleave) {
                this.firstleave = false;
                if (!to.meta.isPoly && from.meta.isPoly && !to.query.isTurn) {
                    let lastSystem = JSON.parse(localStorage.getItem("lastSystem"));
                    next({
                        name: "welcome",
                        query: {
                            system: lastSystem
                        }
                    });
                }
            }
            next();
        },
        // beforeRouteEnter(to, from, next) {
        //     // 修复iOS版微信h5 History兼容性问题
        //     if (isIOS() && to.path !== location.pathname) {
        //         location.assign(to.fullPath); // 此处不可使用location.replace
        //     } else {
        //         next();
        //     }
        // },
        components: { SysCard, Confirm, PassPop, polyQrcode }
    };
</script>

<style lang="stylus" scoped>
    @import '~assets/main.styl';

    * {
        box-sizing: border-box;
    }

    .poly-container {
        position: relative;
        width: 100vw;
        margin-bottom: vw(55);

        .header {
            height: vw(325);
            margin-bottom: titleMargin;

            .banner {
                position: relative;
                height: vw(140);
                padding: vw(25) cellPadding;
                background: main-liner;

                /* flex-y(space-between,flex-start) */
                .top {
                    flex-x(space-between, flex-start);
                    height: vw(50);

                    .left {
                        width: vw(50);
                        height: vw(50);
                        margin-right: smallMargin;

                        img {
                            width: vw(50);
                            height: vw(50);
                            border-radius: all-radius;
                        }
                    }

                    .right {
                        flex: 1;
                        height: vw(50);
                        flex-y(space-between, flex-start);
                        padding: vw(3) 0;

                        p:nth-child(1) {
                            word-vw(word16, grayF);
                            line-height: vw(21);
                        }

                        p:nth-child(2) {
                            word-vw(word12, grayF);
                            line-height: vw(16);
                        }
                    }
                }

                .bottom {
                    margin-top: middleMargin;
                    height: vw(19);
                    flex-x();

                    span {
                        word-vw(word14, grayF);
                        line-height: vw(19);
                    }
                }

                .exit-icon {
                    width: vw(22);
                    height: vw(22);
                    fill: grayF;
                    position: absolute;
                    top: cellPadding;
                    right: vw(54);
                }

                .setting-icon {
                    width: vw(22);
                    height: vw(22);
                    fill: grayF;
                    position: absolute;
                    top: cellPadding;
                    right: cellPadding;
                }
            }

            .code {
                height: vw(45);
                padding: 0 cellPadding;
                flex-x();
                background-color: grayF;
                margin-bottom: 1px;

                .left {
                    flex: 1;
                    flex-x(flex-start, center);

                    .code-icon {
                        width: vw(22);
                        height: vw(22);
                        fill: gray6;
                    }

                    span {
                        line-height: vw(22);
                        margin-left: smallMargin;
                        word-vw(word14, gray3);
                    }
                }

                .icon {
                    width: vw(8);
                    height: vw(12);
                    fill: gray6;
                }
            }
        }

        .main {
            width: 100vw;

            .brand {
                .title {
                    padding: 0 cellPadding;
                    height: vw(48);
                    flex-x();

                    .left {
                        flex-x();

                        span {
                            word-vw(word14, gray3);
                            line-height: vw(19);
                        }

                        .icon {
                            width: vw(16);
                            height: vw(20);
                            fill: #000000;
                            margin-left: cellPadding;
                        }
                    }

                    .right {
                        span {
                            word-vw(word12, gray3);
                            line-height: vw(16);
                            margin-right: smallMargin;
                        }
                    }

                    .icon {
                        width: vw(8);
                        height: vw(12);
                        fill: gray6;
                    }
                }
            }
        }

        .footer {
            margin-top: cellPadding;
            margin-bottom: cellPadding;
            padding: 0;

            .note {
                margin: titleMargin cellPadding;
                word-vw(word12, gray9);
                line-height: vw(16);
            }

            .spread {
                margin: vw(40) 0 middleMargin 0;
                padding: titleMargin 0;
                text-align: center;

                img {
                    width: vw(128);
                    height: vw(128);
                    margin-bottom: smallMargin;
                }

                p {
                    word-vw(word14, gray3);
                    line-height: vw(19);
                }
            }
        }

        .btnWrapper {
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100vw;
            height: vw(55);
            background-color: grayF;
            flex-x(center);
            box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1);

            .bind-apply {
                big-solid();
            }
        }
    }
</style>
